package EventSystem

import (
	//"fmt"
	"strings"

	. "git.oschina.net/yangdao/extlib/data_type"
)

var GlobalEventManager *TypEventManager

func init() {
	GlobalEventManager = NewEventManager()
}

type TypEventManager struct {
	EventHandles *TypMap
}

func NewEventManager() *TypEventManager {
	return &TypEventManager{EventHandles: HashMap()}
}

func (this *TypEventManager) CallEvent(eventPath string, args ...interface{}) {
	curHandler := this.FindHandler(eventPath)
	if curHandler != nil {
		curHandler.DispatchEvent(args...)
	}
}

func (this *TypEventManager) AddEventHandler(eventPath string, fn EventHandleFunc) *EventHandleFuncData {
	eventPathArr := strings.Split(eventPath, ".")
	PreEventHandler := this.newGetEventHandler(this.EventHandles, eventPathArr[0])
	for i := 1; i < len(eventPathArr); i++ {
		curEventName := eventPathArr[i]
		PreEventHandler = this.newGetEventHandler(PreEventHandler.ChildHandles, curEventName)
	}
	return PreEventHandler.AddHandler(fn)
}

func (this *TypEventManager) newGetEventHandler(oldDic IAssociative, keyName string) *EventHandler {
	if !oldDic.ContainsKey(keyName) {
		oldDic.Assoc(keyName, NewEventHandler(keyName))
	}
	return oldDic.Get(keyName).(*EventHandler)
}

func (this *TypEventManager) FindHandler(eventPath string) *EventHandler {
	eventPathArr := strings.Split(eventPath, ".")
	if !this.EventHandles.ContainsKey(eventPathArr[0]) {
		return nil
	}
	preHandle := this.EventHandles.Get(eventPathArr[0]).(*EventHandler)
	for i := 1; i < len(eventPathArr); i++ {
		curEventName := eventPathArr[i]
		if !preHandle.ChildHandles.ContainsKey(curEventName) {
			return nil
		}
		preHandle = preHandle.ChildHandles.Get(curEventName).(*EventHandler)
	}
	return preHandle
}

func (this *TypEventManager) RemoveHandler(eventPath string, fn *EventHandleFuncData) {
	this.FindHandler(eventPath).RemoveHandler(fn)
}
